package com.mipo.client.javase.cas.client;

import java.io.IOException;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public final class Client {
	private static final Logger LOG = Logger.getLogger(Client.class.getName());

	public static void main(final String[] args) throws Exception {
		final String service = "http://localhost:8080/service"; // 随意写
		
		String TGT = getTicketGrantingTicket("http://localhost:8443/cas/v1/tickets", "jack", "123456"); // 获取TGT
		System.out.println("获取TGT为:" + TGT);
		String ST = getServiceTicket("http://localhost:8443/cas/v1/tickets/" + TGT, service); // 获取ST
		System.out.println("获取ST为:" + ST);
		String resultInfo = getLoginUserInfo("http://localhost:8443/cas/serviceValidate", ST, service); // 获取用户信息
		System.out.println("获取用户信息为:" + resultInfo);
		logout("http://localhost:8443/cas/v1/tickets/" + TGT); // 注销退出登录
	}
	
	public static String logout(String url) throws Exception {
		final HttpClient client = new HttpClient();
		final DeleteMethod delete = new DeleteMethod(url);
		client.executeMethod(delete);
		final String response = delete.getResponseBodyAsString();
		return response;
		
	}
	
	
	public static String getLoginUserInfo(String url, String st, String service) throws Exception {
		final HttpClient client = new HttpClient();
		final PostMethod post = new PostMethod(url);
		post.setRequestBody(new NameValuePair[] {new NameValuePair("ticket", st), new NameValuePair("service", service)});
		client.executeMethod(post);
		final String response = post.getResponseBodyAsString();
		return response;
	}
	
	private static String getServiceTicket(final String url, final String service) {
		final HttpClient client = new HttpClient();
		final PostMethod post = new PostMethod(url);
		post.setRequestBody(new NameValuePair[] {new NameValuePair("service", service)});
		try {
			client.executeMethod(post);
			final String response = post.getResponseBodyAsString();
			switch (post.getStatusCode()) {
			case 200:
				return response;
			default:
				LOG.warning("Invalid response code (" + post.getStatusCode() + ") from CAS server!");
				LOG.info("Response (1k): " + response.substring(0, Math.min(1024, response.length())));
				break;
			}
		} catch (final IOException e) {
			LOG.warning(e.getMessage());
		} finally {
			post.releaseConnection();
		}
		return null;
	}

	private static String getTicketGrantingTicket(final String server, final String username, final String password) {
		final HttpClient client = new HttpClient();
		final PostMethod post = new PostMethod(server);
		post.setRequestBody(new NameValuePair[] {new NameValuePair("username", username), new NameValuePair("password", password)});
		try {
			client.executeMethod(post);
			final String response = post.getResponseBodyAsString();
			System.out.println("获取TGT原始报文：" + response);
			switch (post.getStatusCode()) {
			case 201: {
				final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response);
				if (matcher.matches()){
					String TGT = matcher.group(1);
					return TGT;
				}
				LOG.warning("Successful ticket granting request, but no ticket found!");
				LOG.info("Response (1k): " + response.substring(0, Math.min(1024, response.length())));
				break;
			}
			default:
				LOG.warning("Invalid response code (" + post.getStatusCode() + ") from CAS server!");
				LOG.info("Response (1k): " + response.substring(0, Math.min(1024, response.length())));
				break;
			}
		} catch (final IOException e) {
			LOG.warning(e.getMessage());
		} finally {
			post.releaseConnection();
		}
		return null;
	}
	

	
}